package com.lfs.adapter.service.impl;

import com.lfs.adapter.base.LfsGameAdapter;
import com.lfs.adapter.service.ChannelSupplierService;
import com.lfs.adapter.service.GameOrderInfoService;
import com.lfs.adapter.service.GameOrderService;
import com.lfs.adapter.util.JsonObjectUtil;
import com.lfs.common.constant.CommonConstants;
import com.lfs.common.constant.Constant;
import com.lfs.interfaces.dto.ResultReturn;
import com.lfs.base.util.CollectionUtils;
import com.lfs.interfaces.model.ChannelSupplier;
import com.lfs.interfaces.model.GameBaseResponse;
import com.lfs.interfaces.model.NotifyModel;
import com.lfs.interfaces.model.dto.OrderCharge;
import com.lfs.interfaces.model.dto.OrderDto;
import com.lfs.interfaces.model.dto.OrderNotifyDto;
import com.lfs.interfaces.model.vo.ChargeVo;
import com.lfs.interfaces.order.service.OrderBaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class GameOrderServiceImpl implements GameOrderService {

    private Logger logger = LoggerFactory.getLogger(GameOrderServiceImpl.class);

    @Autowired
    private GameOrderInfoService gameOrderInfoService;

    @Autowired
    private ChannelSupplierService channelSupplierService;

    @Autowired
    private OrderBaseService orderBaseService;

    @Override
    public ResultReturn<ChargeVo> makeOrder(OrderDto orderDto) {
        ChargeVo vo = new ChargeVo();
        vo.setApplyTime(Constant.getDateTime());
        vo.setReqStreamId(orderDto.getDownOrderNo());
        vo.setBalance(orderDto.getBalance());
        vo.setOrderNo(orderDto.getOrderNo());
        vo.setChargeNumBalance(new BigDecimal(0));
        ResultReturn<ChargeVo>  response = new ResultReturn<>();
        if (orderDto.getAdapterName() == null  || orderDto.getDownOrderNo()== null
                || orderDto.getUpchanel() == null) {
            response.setStatus(CommonConstants.RESP_CHARGE_FAIL).setData(vo,new OrderDto()).setMsg("缺少必要参数");
            return response;
        }
        try {
            logger.info("【提交订单】调用适配器下发记录开始  orderId = {}，channel ={},adapterName ={}", orderDto.getDownOrderNo(),
                    orderDto.getUpchanel(), orderDto.getAdapterName());
            ChannelSupplier config = channelSupplierService.queryChannelConfigByCodeCache(orderDto.getUpchanel());
            if (config != null) {
                LfsGameAdapter adapter = (LfsGameAdapter) Class.forName(orderDto.getAdapterName()).newInstance();
                //查询数据库中是否存在此订单
                Map<String,Object> mobileRec = gameOrderInfoService.getIfExistOrder(orderDto.getDownOrderNo());
                if (mobileRec == null) {
                    logger.error("【提交订单】下发记录表没记录  orderId = {}", orderDto.getDownOrderNo());
                    response.setStatus(CommonConstants.RESP_CHARGE_FAIL).setData(vo,new OrderDto()).setMsg("订单号不存在");
                    return response;
                } else {
                    // 内部标准协议返回
                    logger.info("【提交订单】调用适配器下发记录  orderId = {}", orderDto.getDownOrderNo());
                    /**
                     * 根据平台产品编号去查找上游产品编号
                     */
                    if(orderDto.getProductCode()!=null){
                        Map<String,Object> resultMap=gameOrderInfoService.getUpProductNo( orderDto.getProductCode(),orderDto.getUpchanel());
                        if(resultMap!=null){
                            orderDto.setUpProductCode((String)resultMap.get("upProductCode"));
                        }
                    }
                    response= adapter.makeOrder(orderDto, config);
                    logger.info("【提交订单】调用适配器下发记录结束  orderId = {}，response = {}", orderDto.getOrderNo(), JsonObjectUtil.object2json(response));

                    //上游返回充值成功
                    logger.info("上游充值返回state={}",response.getOrder().getState());
                }
            } else {
                logger.error("【提交订单】通道不存在 {},channel={}",orderDto.getUpchanel());
                response.setStatus(CommonConstants.RESP_CHARGE_ERROR).setData(vo,new OrderDto()).setMsg("通道不存在");
                return response;
            }
        } catch (Exception e) {
            if (e instanceof ClassNotFoundException) {
                logger.error("【提交订单】适配器不存在 {}", orderDto);
                response.setStatus(CommonConstants.RESP_CHARGE_FAIL).setData(vo,new OrderDto()).setMsg("适配器不存在");
                return response;
            } else {
                logger.error("【提交订单】内部错误 {}", e);
                response.setStatus(CommonConstants.RESP_CHARGE_HANDLE).setData(vo,new OrderDto()).setMsg("服务器内部错误");
                return response;
            }
        }
        return response;
    }

    public String notify(NotifyModel model) {
        OrderCharge order = new OrderCharge();
        OrderCharge orderInfo = null;
        order.setOrderNo(model.getOrderNo());
        List<OrderCharge> orders = orderBaseService.getValidOrderForConfirmByBuscodeAndOrderNo(order);
        if(CollectionUtils.isNotEmpty(orders)){
            orderInfo = orders.get(0);
        }
        Map<String,Object> map=channelSupplierService.getNotifyInfo(model.getOrderNo());
        String result= "";
        if(map==null || map.get("adapterName")==null || CommonConstants.ADAPTER_NOTIFY_STATUS.equals(model.getStatus())){
            if(map!=null && map.get("reqStreamId") !=null){
                logger.info("【调用适配器】，上游返回失败,orderNo={}",model.getOrderNo());
                OrderNotifyDto orderNotify = new OrderNotifyDto();
                orderNotify.setAgtPhone(map.get("agtPhone")+"");
                orderNotify.setReqStreamId(map.get("reqStreamId")+"");
                orderNotify.setOrderNo(model.getOrderNo());
                orderNotify.setPrice(new BigDecimal(map.get("price").toString()));
                orderNotify.setState(1);
                orderBaseService.sendNotify(orderNotify);
                return Constant.RET_SUCCESS;
            }else{
                logger.error("【回调未找到适配器】,orderNo={},fail={}",model.getOrderNo(),model.getStatus());
            }
            return Constant.RET_EXCEPTION;
        }else{

        }

        try {
            LfsGameAdapter adapter = (LfsGameAdapter) Class.forName(map.get("adapterName").toString()).newInstance();
            result= adapter.handleCallback(model.getOrderNo(), model.getStatus(), model.getUpOrderNo());
        } catch (InstantiationException | IllegalAccessException
                | ClassNotFoundException e) {
            logger.error("【回调出现异常】,e={}",e.getMessage());
        }
        return result;
    }

    public String queryBalance(String channelCode) {

        logger.info("通道查询余额，通道编码： channelcode = {}", channelCode );
        ChannelSupplier config = channelSupplierService.queryChannelConfigByCodeCache(channelCode);

        String returnStr = "";
        if (config != null) {
            try {
                BigDecimal balanceMoney = null;
                returnStr = "nodata";
                LfsGameAdapter adapter = (LfsGameAdapter) Class.forName(config.getAdapterName()).newInstance();
                balanceMoney = adapter.queryBalance(config);

                if(null != balanceMoney)
                {
                    returnStr = balanceMoney+"";
                }

            } catch (Exception e) {
                if (e instanceof ClassNotFoundException) {
                    logger.error("【查询余额】适配器不存在 {}", channelCode);
                } else {
                    logger.error("【查询余额】内部错误 {}", e);
                }
            }
        } else {
            logger.error("通道不存在 {},channel={}",channelCode);
        }
        return returnStr;
    }

    /**
     * 查询接口
     * @param orderNo
     * @return
     */
    public GameBaseResponse queryInfo(String orderNo) {
        GameBaseResponse baseResponse = new GameBaseResponse();

        OrderDto orderInfo = orderBaseService.getOrderInfo(orderNo);
        if(null == orderInfo)
        {
            baseResponse.setFailResponse("该订单不存在或已经处理！");
            logger.info("该订单不存在或已经处理！ orderNo={}",orderNo);
            return baseResponse;
        }

        if( orderInfo.getChargeAddr() == null || orderInfo.getDownOrderNo()== null
                || orderInfo.getUpchanel() == null || orderInfo.getOrderNo() == null)
        {
            baseResponse.setFailResponse("缺少必要参数");
            logger.info("缺少必要参数！ orderNo={}",orderNo);
            return baseResponse;
        }

        ChannelSupplier config = channelSupplierService.queryChannelConfigByCodeCache(orderInfo.getUpchanel());
        if(null != config)
        {
            try {

                LfsGameAdapter adapter = (LfsGameAdapter)Class.forName(config.getAdapterName()).newInstance();
                baseResponse = adapter.queryOrder(orderInfo, config);

            } catch (Exception e) {
                if (e instanceof ClassNotFoundException) {
                    baseResponse.setFailResponse("适配器类不存在");
                    logger.info("适配器类不存在！ orderNo={}",orderNo);
                    return baseResponse;
                } else {
                    baseResponse.setFailResponse("查询内部错误");
                    logger.info("查询内部错误！ orderNo={}",orderNo);
                    return baseResponse;
                }
            }
        }
        return baseResponse;
    }
}
